<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId" :isPropagation="false">
    <template v-slot:common>
      <div v-if="isPicker" class="wb-dropdown" :data-id="item.id">
        <van-cell is-link @click="onShowPicker" :style="styles" ref="dropdown">{{ selectedValue }}</van-cell>
        <van-popup v-model:show="showPicker" teleport="body" position="bottom" round>
          <van-picker show-toolbar :title="title" :columns="options" @cancel="onHidePicker" @confirm="onConfirm"/>
        </van-popup>
      </div>
      <div v-else class="wb-dropdown" :data-id="item.id">
        <van-dropdown-menu :overlay="false">
          <van-dropdown-item v-model="selectedValue" :options="options" @change="onPCConfirm"/>
        </van-dropdown-menu>
      </div>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { formUtils } from '@/components/form/js/form-utils'
import { EventBus } from '@/store/index'
import { reactive } from 'vue'
import { isHasOwnProperty } from '@/plugins/utils'


export default {
  name: 'WbDropdown',
  mixins: [utils, commonUtils, formUtils],
  setup (props) {
    const state = reactive({
      title: props.item.commonAttr.title,
      showPicker: false,
      selectedValue: props.item.commonAttr.placeholder,
    })
    const state_ = {
      selectedIndex: -1,
      customList: [],
    }
    _.merge(state, state_)
    return state
  },
  components: {
    InjectTemplate,
  },
  computed: {

    disabled() {
      if (this.isH5Edit) {
        return true;
      } else {
        return false;
      }
    },
    isPicker() {
      return this.isH5Edit || (this.siteInfo.md.isMobile && !this.commonAttr.isMenu)
    },
    /* eslint-disable */
    options() {
      let lists_ = [];
      // this.commonAttr.isCustomData = true;
      if(this.commonAttr.isCustomData){
        // {
        //   "西北地区": {
        //     "texts": ["新疆", "内蒙", "甘肃"],
        //     "index": 3
        //   },
        //   "青藏地区": {
        //     "texts": ["西藏", "青海", "四川"],
        //     "index": 4
        //   },
        //   "北方地区": {
        //     "texts": ["黑龙江", "吉林", "辽宁", "北京", "天津", "河北", "山西", "陕西", "宁夏", "河南", "山东"],
        //     "index": 1
        //   },
        //   "南方地区": {
        //     "texts": ["海南", "澳门", "香港", "台湾", "广东", "广西", "福建", "江西", "贵州", "湖南", "重庆", "湖北", "安徽", "江苏", "浙江", "上海", "云南"],
        //     "index": 2
        //   },
        //   "海外": {
        //     "texts": ["海外"],
        //     "index": 5
        //   }
        // }
        // this.customData = {
        //   "西北地区":["新疆","内蒙","甘肃"],
        //   "青藏地区":["西藏","青海","四川"],
        //   "北方地区":["黑龙江","吉林","辽宁","北京","天津","河北","山西","陕西","宁夏","河南","山东"],
        //   "南方地区":["海南","澳门","香港","台湾","广东","广西","福建","江西","贵州","湖南","重庆","湖北","安徽","江苏","浙江","上海","云南"],
        //   "海外":['海外'],
        // };
        // this.commonAttr.firstKey = "西北地区";
        // const firstKey = this.commonAttr.customDataFirstKey;
        // lists_ = [{ values: Object.keys(this.customData) }, { values: this.customData[firstKey] }];
        // [{
        //   text:'西北地区',
        //   children:[{text:'新疆'},{text:'内蒙'},{text:'甘肃'}],
        // }]
        const customData = this.commonAttr.customData && JSON.parse(this.commonAttr.customData);
        _.forEach(customData, (item, key, index) => {
          let obj = {
            text: key,
            children: [],
            index,
          }
          if(_.isArray(item)){
            _.forEach(item, (text) => {
              obj.children.push({ text })
            })
          }else{
            _.forEach(item.texts, (text) => {
              obj.children.push({ text })
            })
            obj.index = item.index;
          }
          lists_.push(obj)
        });
        lists_ = _.sortBy(lists_, (item) => { return item.index; });
        this.customList = lists_
      }else{
        if(this.isWbLists){
           _.forEach(this.wbLists, (item, index) => {
             //好友列表 id name pic_url
             if(item.value){
               lists_.push({text: item.name, value: item.value})
             }else{
               lists_.push({text: item.name, value: index})
             }
          })
        }else{
          _.forEach(this.item.lists, (item, index) => {
            lists_.push({text: item.text, value: index});
          })
        }
      }
      return lists_
    },
  },
  created() {
    if(this.isH5Edit){
      return
    }
    EventBus.$off("refreshFriends", this.onUpdateFormValue)
    EventBus.$on("refreshFriends", this.onUpdateFormValue)

    this.selectedIndex = this.commonAttr.isDefaultSelected ? 0 : -1;
    let options_ = this.options
    if(this.commonAttr.isMenu || !this.siteInfo.md.isMobile) {
      this.selectedValue = options_[0] ? options_[0].value : ''
    } else {
      this.selectedValue = options_[0] ? options_[0].text : ''
      if(this.item.commonAttr.placeholder){
        this.selectedValue = this.item.commonAttr.placeholder
      }
    }
  },
  mounted(){
    this.setArrowBtnColor();
    if(this.selectedValue && this.commonAttr.placeholder && this.$refs.dropdown) {
      this.$refs.dropdown.$el.style.color = this.commonAttr.placeholerColor;
    }
  },
  methods: {
    setArrowBtnColor(){
      let arrowBtn = this.$el && this.$el.getElementsByClassName('van-icon-arrow')[0];
      if(isHasOwnProperty(this.commonAttr, "arrowBtnColor") && arrowBtn){
        arrowBtn.style.color = this.commonAttr.arrowBtnColor;
        this.arrowBtnColor = this.commonAttr.arrowBtnColor
      }
    },
    onHidePicker(){
      this.showPicker = false
      this.$store.commit("updateComponentAttr", { id: this.item.id, conStyles: { zIndex: this.item.conStyles.oriZIndex } });
    },
    onConfirm(item, index) {
      if(_.isArray(item)){
        let str = '';
        let len = item.length - 1;
        _.forEach(item, (item_, index_) => {
          str += item_.text;
          if(index_ != len){
            str += "/"
          }
        })
        this.selectedValue = str
        this.selectedIndex = index[0]
      }else{
        this.selectedValue = item.text
        this.selectedIndex = index
      }

      this.onHidePicker()
      this.$refs.dropdown.$el.style.color = this.commonAttr.color;
    },
    onPCConfirm(index) {
      this.selectedValue = this.options[index].value
      this.selectedText = this.options[index].text
      this.selectedIndex = index
      this.$refs.dropdown.$el.style.color = this.commonAttr.color;

      this.updateInteractionData();

      let jumpUrl = "dropdown_" + index
      let comType = "click"
      let wModule = "jump"
      this.onPostStatics(null, { comType, wModule,  jumpUrl })
    },
    onShowPicker(){
      this.showPicker = true
      //解决ios bug 不能设置 bottom top不能理解为啥
      const swiperVertical = document.getElementsByClassName("swiper-container-vertical")[0];
      if(this.siteInfo.md.isIPhone && swiperVertical){
        setTimeout(() => {
          const vanPopups = this.$el.getElementsByClassName("van-popup--bottom");
          _.forEach(vanPopups, (vanPopup) => {
            if(vanPopup){
              this.removeClass(vanPopup, "van-popup--bottom");
              vanPopup.style.width = "100vw";
              vanPopup.style.height = "100vh";
              vanPopup.style.left = "0";
              vanPopup.style.right = "0";
            }
          })
        }, 50)
      }
      
      this.$store.commit("updateComponentAttr", { id: this.item.id, conStyles: { zIndex: 20, oriZIndex: this.item.conStyles.zIndex } });
    },
    updateFormValue(){
      let item
      let lists_
      if(this.commonAttr.isCustomData){
        item = this.customList[this.selectedIndex];
      }else{
        if(this.isWbLists){
          lists_ = this.wbLists
        }else{
          lists_ = this.item.lists
        }
        item = lists_[this.selectedIndex]
      }
      if(item) {
        this.$store.commit('updateFormValue', { id: this.item.id, value: this.selectedValue, item });
        EventBus.$emit("itemClick", {id: this.item.id, index: this.selectedIndex});
      }
    },
    onUpdateFormValue({ id }){
      //页面上有添加微博用户数据的组件，同时又有下拉列表，这时不需要刷新下拉列表的选中属性，而是使用默认的配置提示
      if(this.item.id != id || this.selectedIndex < 0){
        return
      }
      let lists_;
      let item;
      if(this.commonAttr.isCustomData){
        lists_ = this.customData[this.commonAttr.customDataFirstKey];
        item = { text: lists_[0] }
      }else{
        if(this.isWbLists){
          lists_ = this.wbLists;
        }else{
          lists_ = this.item.lists;
        }
        item = lists_[this.selectedIndex];
      }
      const value = item && (item.name || item.text) || '';
      this.selectedValue = value;
    },
    onRefreshCommonAttr() {
      if(this.arrowBtnColor != this.commonAttr.arrowBtnColor){
        this.setArrowBtnColor();
      }
    },
  },
  watch: {
    selectedValue() {
      if(this.isH5Edit){
        return
      }
      this.updateFormValue()
    },
  },
  beforeUnmount(){
    if(this.isH5Edit){
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
      return
    }
    EventBus.$off("refreshFriends", this.onUpdateFormValue)
  }
};
</script>

<style lang="scss">
.wb-dropdown {
  width: inherit;
  height: inherit;

  .van-dropdown-menu {
    width: inherit;
    background-color: transparent;

    .van-dropdown-item {
      width: inherit;
      left: auto;
      right: auto;
    }
    .van-dropdown-item__option {
      text-align: center;
    }
  }
}
</style>
